package com.x.Servlet_03_ServletConfig;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Enumeration;

/**
 * ClassName: ServletConfigTest2
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.08.06 21:43
 */
@WebServlet(
        urlPatterns = "/ServletConfig2",
        initParams = {@WebInitParam(name = "key-4", value = "value-4"),
                @WebInitParam(name = "key-5", value = "value-5"),
                @WebInitParam(name = "key-6", value = "value-6")}
)

public class ServletConfigTest2 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("************ServletConfig获取参数*************");

        jakarta.servlet.ServletConfig servletConfig = super.getServletConfig();
        String initParameter = servletConfig.getInitParameter("key-1");
        System.out.println("key-1: " + initParameter);
        System.out.println("******************");

        Enumeration<String> initParameterNames = servletConfig.getInitParameterNames();
        //旧版本的迭代器
        //hasMoreElements():判断是否存在下一个参数，存在返回true，否则返回false
        //nextElement():取出元素、向下移动一位指针
        while (initParameterNames.hasMoreElements()){
            String element = initParameterNames.nextElement();
            String initParameter1 = servletConfig.getInitParameter(element);
            System.out.println(element+": "+initParameter1);
        }


        System.out.println("************ServletContext获取参数*************");

        ServletContext servletContext = super.getServletContext();
        String initParameter1 = servletContext.getInitParameter("encoding");
        System.out.println("encoding: " + initParameter1);


    }
}
